package com.bds.tjj.service;

import java.net.URLDecoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.nutz.dao.Cnd;
import org.nutz.dao.impl.NutDao;
import org.springframework.stereotype.Service;

import com.bds.tjj.model.MonthData;
import com.bds.tjj.model.PropIndex;
import com.bds.tjj.utils.Const;

/**
 * Created by guoyu on 2018/1/29.
 */
@Service
public class MonthSumService {
    private static final org.apache.log4j.Logger LOGGER = org.apache.log4j.Logger.getLogger(MonthSumService.class);
    private static final DecimalFormat df = new DecimalFormat("#.0");

    @Resource
    private NutDao dao;

    @Resource
    private UserService userService;

    public MonthData getMonthNum(String type) throws Exception {
        type = URLDecoder.decode(type, "utf-8");
        List<MonthData> monthDataList = dao.query(MonthData.class, Cnd.where("prop", "=", type)
                .and("data", "is not", null).and("data", "<>", "").limit(1, 2).orderBy("ym", "desc"));

        if (monthDataList.size() > 0) {
            MonthData monthData = monthDataList.get(0);
            MonthData monthDataAgo = monthDataList.get(1);
            PropIndex pi = dao.fetch(PropIndex.class, Cnd.where("prop", "=", type));
            if (pi != null) {
                monthData.setUnit(pi.getUnit());
            }

            Integer ym = monthData.getYm();
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMM");
            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy/MM");
            if (ym != null) {
                Date yearMonth = sdf1.parse(ym + "");
                String vym = sdf2.format(yearMonth);
                monthData.setView_ym(vym);
            }

            if (monthData.getData() != null && monthData.getData().contains(".")) {
                // 小数点后是否大于4位
                if (monthData.getData().split("\\.")[1].length() > Const.decimal_num) {
                    monthData.setData(df.format(Double.parseDouble(monthData.getData())));
                }
            }

            //计算IYA
            try {
                Integer preYm = monthData.getYm() - 100;
                MonthData preYmData = dao.fetch(MonthData.class, Cnd.where("prop", "=", type)
                        .and("data", "is not", null).and("data", "<>", "")
                        .and("ym", "=", preYm));

                if (preYmData != null) {
                    if (monthData.getData() != null && (!monthData.getData().equals(""))) {
                        double a = Double.parseDouble(monthData.getData()) - Double.parseDouble(preYmData.getData());
                        double b = Math.abs(Double.parseDouble(preYmData.getData()));
                        double r = (a * 1.0 / b) * 100;
                        monthData.setIya(Double.parseDouble(df.format(r)));
                    } else {
                        monthData.setIya(null);
                    }
                } else {
                    monthData.setIya(null);
                }
            } catch (Exception e) {
                monthData.setIya(null);
            }

            //计算IPP
            try {
                String[] yms = new String[2];
                yms[0] = monthDataAgo.getYm() + "";
                yms[1] = monthData.getYm() + "";

                if (this.isMonthNext(yms)) {
                    if (monthData.getData() != null && (!monthData.getData().equals(""))) {
                        double a = Double.parseDouble(monthData.getData()) - Double.parseDouble(monthDataAgo.getData());
                        double b = Math.abs(Double.parseDouble(monthDataAgo.getData()));
                        double r = (a * 1.0 / b) * 100;
                        monthData.setYya(Double.parseDouble(df.format(r)));
                        monthData.setIpp(Double.parseDouble(df.format(r)));
                        monthData.setAbs(Double.parseDouble(df.format(a)));
                    } else {
                        monthData.setYya(null);
                        monthData.setIpp(null);
                        monthData.setAbs(null);
                    }
                } else {
                    monthData.setYya(null);
                    monthData.setIpp(null);
                    monthData.setAbs(null);
                }
            } catch (Exception e) {
                monthData.setYya(null);
                monthData.setIpp(null);
                monthData.setAbs(null);
            }

            return monthData;
        } else {
            return new MonthData();
        }

    }

    public boolean isMonthNext(String[] years) {
        Arrays.sort(years);
        String fyearsIndex = years[0].substring(0, 4);
        String syearsIndex = years[1].substring(0, 4);
        String fyearLast = years[0].substring(4, 6);
        String syearLast = years[1].substring(4, 6);
        if (fyearsIndex.equals(syearsIndex)) {
            if (Integer.valueOf(syearLast) - Integer.valueOf(fyearLast) == 1)
                return true;
        } else if (Integer.valueOf(syearsIndex) - Integer.valueOf(fyearsIndex) == 1 && Integer.valueOf(fyearLast) == 12
                && Integer.valueOf(syearLast) == 1) {
            return true;
        }
        return false;

    }

    public MonthData getLastMonth() throws Exception {

        List<MonthData> ls = dao.query(MonthData.class, Cnd.NEW().limit(1, 1).desc("ym"));
        if (ls != null && ls.size() > 0) {
            return ls.get(0);
        } else {
            return null;
        }
    }

    public PropIndex getPropIndex(String prop) throws Exception {

        PropIndex pos = dao.fetch(PropIndex.class, Cnd.where("prop", "=", prop));

        return pos;
    }

    public List<MonthData> getMonthTips() throws Exception {

        List<PropIndex> ps = userService.getDataSelect("month");
        List<MonthData> ys = new ArrayList<MonthData>();
        for (int i = 0; i < ps.size(); i++) {
            PropIndex pi = ps.get(i);

            MonthData yy = this.getMonthNum(pi.getProp());
            if (yy != null) {
                if (i % 4 == 0) {
                    yy.setStyle_class("success");
                } else if (i % 4 == 1) {
                    yy.setStyle_class("info");
                } else if (i % 4 == 2) {
                    yy.setStyle_class("important");
                } else if (i % 4 == 3) {
                    yy.setStyle_class("warning");
                }
                ys.add(yy);
            } else {
                LOGGER.error("没有此指标:" + pi.getCn_name());
            }

        }

        return ys;

    }

    public List<MonthData> getMonthTips(String tabName) throws Exception {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_MONTH, -7);
        Date lastdate = cal.getTime();
        List<PropIndex> ps = userService.getDataSelect("month", tabName);
        List<MonthData> ys = new ArrayList<MonthData>();
        for (int i = 0; i < ps.size(); i++) {
            PropIndex pi = ps.get(i);
            if (pi.getIs_area() == 1) {
                continue;
            }
            MonthData yy = this.getMonthNum(pi.getProp());

            if (yy != null) {
                yy.setEn_name(pi.getView_name());
                yy.setUnit(pi.getUnit());
                if (yy.getCreate_time().after(lastdate)) {
                    yy.setIsnew("1");
                } else {
                    yy.setIsnew("0");
                }
                if (i % 4 == 0) {
                    yy.setStyle_class("success");
                } else if (i % 4 == 1) {
                    yy.setStyle_class("info");
                } else if (i % 4 == 2) {
                    yy.setStyle_class("important");
                } else if (i % 4 == 3) {
                    yy.setStyle_class("warning");
                }
                ys.add(yy);
            } else {
                LOGGER.error("没有此指标:" + pi.getCn_name());
            }

        }

        return ys;

    }

    public List<MonthData> getMonthTrend(String type, int startTime, int endTime) throws Exception {
        type = URLDecoder.decode(type, "utf-8");
        List<MonthData> list = dao.query(MonthData.class,
                Cnd.where("prop", "=", type).and("ym", ">=", startTime).and("ym", "<=", endTime).orderBy("ym", "desc"));

        Collections.reverse(list);

        PropIndex prop = new PropIndex();
        if (list.size() > 0) {
            prop = dao.fetch(PropIndex.class, Cnd.where("prop", "=", list.get(0).getProp()));
        }
        String preData = null;
        for (int i = 0; i < list.size(); i++) {
            MonthData monthData = list.get(i);

            monthData.setUnit(prop.getUnit());
            monthData.setView_name(prop.getView_name());

            if (prop.getIf_rate() == 0) {
                if (i == 0) {
                    monthData.setYya(0.0);
                } else {
                    if (preData != null && (!preData.equals(""))) {
                        if (monthData.getData() != null && (!monthData.getData().equals(""))) {
                            double a = Double.parseDouble(monthData.getData()) - Double.parseDouble(preData);
                            double b = Math.abs(Double.parseDouble(preData));
                            double r = (a * 1.0 / b) * 100;
                            monthData.setYya(Double.parseDouble(df.format(r)));
                        }
                    } else {
                        monthData.setYya(0.0);
                    }
                }
            }

            if (monthData.getData() == null) {
                continue;
            }

            if (prop != null) {
                monthData.setEn_name(prop.getEn_name());
                monthData.setIs_area(prop.getIs_area());
            }
            if (monthData.getData().contains(".")) {
                // 小数点后是否大于4位
                if (monthData.getData().split("\\.")[1].length() > Const.decimal_num) {
                    monthData.setData(df.format(Double.parseDouble(monthData.getData())));
                }
            }

            if (monthData.getData() != null) {
                if (!monthData.getData().equals("")) {
                    preData = monthData.getData();
                }
            }
        }

        Collections.reverse(list);

        return list;
    }
}
